<template>
  <setting-public-view current="repertory" :nav="sparepartNav">
    <div class="setting-box-warp setting-box-warp-part">
      <div class="setting-box" v-if="modelShow">
        <div class="box-title">
          <p>{{$t('sparepart.setting.repertory.title1')}}</p>
        </div>
        <div class="box-body">
          <div class="box-item">
            <div class="repertory_radio_box">
              <div><el-radio v-model="sparepart2" @change="sparepart2Change" :label="0" :disabled="sparepart2==1?true:false">{{$t('sparepart.setting.repertory.label1')}}</el-radio></div>
              <p class="radio_text">{{$t('sparepart.setting.repertory.des1')}}</p>
            </div>
            <div class="repertory_radio_box">
              <div><el-radio v-model="sparepart2" @change="sparepart2Change" :label="1">{{$t('sparepart.setting.repertory.label2')}}</el-radio></div>
              <p class="radio_text">{{$t('sparepart.setting.repertory.des2')}}</p>
              <p class="radio_text">
                <el-checkbox class="item-checkbox" v-model="personalRepertory" @change="personalRepertoryChange">{{$t('sparepart.setting.repertory.label3')}}</el-checkbox>
              </p>
            </div>
          </div>
        </div>
      </div>

      <div class="setting-box">
        <div class="box-title">
          <p>{{$t('sparepart.setting.repertory.title2')}}</p>
        </div>
        <div class="box-body">
          <div class="box-item">
            <div class="setting_search_box" v-if="modelShow">
              <el-input :placeholder="$t('sparepart.setting.repertory.pla1')"
                v-model="keyword"
                class="search_input">
                <!-- v-trim:blur -->
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
              <el-button type="primary" @click="getTableData">{{$t('common.base.search')}}</el-button>
              <el-button type="plain-third"  @click="resetSearch">{{$t('common.base.reset')}}</el-button>
              <div class="search-add">
                <el-button type="primary" @click="addHandle"><i class="el-icon-plus"></i>{{$t('common.base.create')}}</el-button>
                <el-button type="plain-third" @click="imporStorehouse">{{$t('common.base.batchImport')}}</el-button>
              </div>
            </div>
            <el-table
              header-row-class-name="common-list-table-header__v2"
              v-loading="loading.tableData"
              class="item-table"
              :data="tableData"
              :max-height="winHeight"
              style="width: 100%"
              border
              >
                <el-table-column
                  type="index"
                  :label="$t('common.base.SN')"
                  width="60"
                  align="center"
                  :index="(val)=>val+1">
                </el-table-column>
                <el-table-column
                  min-width="100"
                  show-overflow-tooltip
                  prop="name"
                  :label="$t('common.base.warehouse')">
                </el-table-column>
                <el-table-column
                  min-width="100"
                  show-overflow-tooltip
                  prop="description"
                  :label="$t('common.base.description1')">
                </el-table-column>
                <el-table-column
                  min-width="78"
                  show-overflow-tooltip
                  prop="type"
                  :label="$t('common.base.classification')">
                </el-table-column>
                <el-table-column
                  min-width="130"
                  show-overflow-tooltip
                  prop="addressDes"
                  :label="$t('common.base.address')">
                </el-table-column>
                <el-table-column
                  min-width="136"
                  show-overflow-tooltip
                  prop="teamDes"
                  :label="$t('sparepart.setting.repertory.column1')">
                </el-table-column>
                <el-table-column
                  min-width="100"
                  :show-overflow-tooltip="getSparePartPersonalUserNameShowTooltip({})"
                  :label="$t('sparepart.setting.repertory.column2')">
                  <template slot-scope="scope">
                    <template v-if="isOpenData && scope.row.manager && scope.row.manager.length">

                      <template v-for="(item, index) in scope.row.manager">
                        <open-data :key="`${item.staffId}${uuid()}`" type="userName" :openid="item.staffId"></open-data>
                        <ui-separator :index="index" :list="scope.row.manager" :key="`${item}${uuid()}`" />
                      </template>
                    </template>

                    <template v-else>
                      {{scope.row.managerDes}}
                    </template>
                 </template>
                </el-table-column>
                <el-table-column
                  width="100"
                  :label="$t('common.base.operation')">
                  <template slot-scope="scope">
                    <el-button type="text" @click="editHandle(scope.row,scope.$index)">{{$t('common.base.edit')}}</el-button>
                    <el-button v-if="scope.row.isSystem==0" type="text" @click="delHandle(scope.row)">{{$t('common.base.delete')}}</el-button>
                 </template>
                </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="setting-box" v-if="isShowApprovalSetting">
        <div class="box-title">
          <p>{{ $t('sparepart.setting.setApprover.title') }}</p>
        </div>
        <div class="box-body">
          <div class="box-item-wrap">
            <div class="box-item">
              <p class="item-title">{{ $t('servicePrice.record.taskSale')}}</p>
              <p class="item-text">{{ $t('sparepart.setting.setApprover.msg') }}</p>
            </div>
            <el-button type="primary" @click="setApprover">{{ $t('sparepart.setting.setApprover.approverPeople') }}</el-button>
        </div>
        </div>
      </div>
    </div>

    <!-- 仓库设置弹窗 atart -->
    <base-modal :title="$t('sparepart.setting.repertory.title3')" :show.sync="isRepertoryModal" width="700px" class="setting-public-dialog">
      <div class="modal_box">
        <el-form label-position="top" :model="repertoryForm" :rules="repertoryRules" ref="repertoryRef" >
          <el-form-item :label="$t('sparepart.setting.repertory.form1')" prop="name">
            <el-input v-model="repertoryForm.name" :placeholder="$t('sparepart.setting.repertory.tips11', {maxLength: '20'})" maxlength="20"></el-input>
          </el-form-item>

          <el-form-item :label="$t('sparepart.setting.repertory.form2')">
            <el-select v-model="repertoryForm.type" :placeholder="$t('common.placeholder.select')">
              <!-- TODO-bdz 中文判断 -->
              <el-option :label="$t('sparepart.setting.repertory.label4')" value="备件库"></el-option>
              <el-option :label="$t('sparepart.setting.repertory.label5')" value="不良品库"></el-option>
              <el-option :label="$t('sparepart.setting.repertory.label6')" value="区域库"></el-option>
              <el-option :label="$t('sparepart.setting.repertory.label7')" value="备件其他库"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('sparepart.setting.repertory.form3')">
            <biz-team-select :value="repertoryForm.teamIds || []" multiple @input="teamUpdate" />
            <!-- collapse is-auto-select-child -->
            <!-- <el-cascader
              size="mini"
              v-model="repertoryForm.teamIds"
              @change="teamIdsChange"
              :options="securityTagTree"
              filterable
              :props="{ checkStrictly: true,multiple: true,value:'id',label:'tagName'}"
              clearable>
            </el-cascader> -->
          </el-form-item>

          <div style="padding-left:110px; position: relative;">
            <div class="el-form-item is-required" style="position: absolute; left:0; top:0;">
              <p class="el-form-item__label" style="line-height:32px;">
                <span>{{$t('sparepart.setting.repertory.title4')}}</span>
                <el-tooltip :content="$t('sparepart.setting.repertory.tips1')" placement="top">
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </p>
            </div>
            <el-form-item prop="manager">
              <!-- <base-select-user-input
                multiple
                v-model="repertoryForm.manager"
                :collapse="false"
                @input="userChange"
              /> -->

              <base-select
                v-model="repertoryForm.manager"
                :remote-method="searchTemplate"
                value-key="userId"
                :placeholder="$t('common.placeholder.select')"
                multiple>
              </base-select>

            </el-form-item>
          </div>

          <el-form-item :label="$t('sparepart.setting.repertory.form4')">
            <el-input type="textarea" :rows="5" v-model="repertoryForm.description" :placeholder="$t('common.base.info')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('sparepart.setting.repertory.form5')">
            <form-address
                :value="repertoryForm"
                @update="update"/>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="plain-third" @click="isRepertoryModal = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" @click="submitRepertory('repertoryRef')">{{$t('common.base.confirm')}}</el-button>
      </div>
    </base-modal>
    <!-- 仓库设置弹窗 end -->
    <!--批量导入仓库 start-->
    <base-import
      :title="$t('sparepart.setting.repertory.title5')"
      ref="imporStorehouse"
      :template-url="sourceListImportTem"
      :action="sourceListImport"
    ></base-import>
    <!--批量导入仓库 end-->

    <!--设置审批人-->
    <work-flow-dialog ref="workFlowDialogRef"></work-flow-dialog>
  </setting-public-view>
</template>
<script>
/* api */
import * as SettingApi from '@src/api/SettingApi.ts';
import { sourceListImportTem, sourceListImport } from '@src/api/Import'

/* util */
import Platform, { isOpenData } from '@src/util/platform';
import { getRootWindow } from '@src/util/dom';

/* components */
import SettingPublicView from '../../components/settingPublicView';
import {sparepartNav} from '../../components/settingPublicView/navList.js';
import WorkflowDialog from '@src/component/compomentV2/AdvancedApproval/WorkflowDialog.vue';

import i18n from '@src/locales'
import { formatAddress } from 'pub-bbx-utils';
/* mixin */
import { VersionControlSparePartMixin } from '@src/mixins/versionControlMixin'

export default {
  name: 'sparepart-repertory',
  mixins: [VersionControlSparePartMixin],
  props: {

  },
  data(){
    return {
      isOpenData,
      sparepartNav:sparepartNav,
      winHeight:null,
      loading:{
        tableData:false,
        page:false,
      },
      list1:[],
      newlist1Type:'',
      radio:0,

      sparepart2:'',//备件库模式
      personalRepertory:false,//个人备件库

      tableData:[],//仓库设置列表
      keyword:'',

      isRepertoryModal:false,
      repertoryForm:{
        name: "",
        type: "备件库",
        teamIds: [],
        manager: [],
        description: "",
        country: "",
        province: "",
        city: "",
        dist: "",
        address: "",
        latitude: "",
        longitude: ""
      },
      repertoryRules:{
        name: [
          { required: true, message: i18n.t('sparepart.setting.repertory.tips2'), trigger: 'blur' },
        ],
        manager: [
          { type: 'array', required: true, message: i18n.t('sparepart.setting.repertory.tips3'), trigger: 'change' }
        ],
      },
      securityTagTree:[],//可选仓库管理人员列表
      securityTagObj:{},
      managerList:[],//可选仓库管理人员列表
      managerObj:{},
      modelShow:false,// 多备件库 显示隐藏
      sourceListImportTem, //导入仓库模板
      sourceListImport, // 导入仓库
    }
  },
  computed: {
    /** 是否开启出入库审批设置 */
    isShowApprovalSetting() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.ADVANCED_APPROVAL_OF_SPARE_PARTS_GRAY ?? false;
    }
  },
  mounted(){
    this.winHeight=window.innerHeight-180;
    this.getConfigData();//获取设置信息
    this.getTableData();
    this.modelShow = this._isShowMoreSpareParts
  },
  components: {
    [SettingPublicView.name]: SettingPublicView,
    [WorkflowDialog.name]: WorkflowDialog
  },
  watch:{
    isRepertoryModal(newVal,oldVal){
      if(!newVal){
        this.$refs.repertoryRef.resetFields();
        this.repertoryForm={
          name: "",
          type: "备件库",
          teamIds: [],
          manager: [],
          description: "",
          country: "",
          province: "",
          city: "",
          dist: "",
          address: "",
          latitude: "",
          longitude: ""
        }
      }
    }
  },
  methods:{
    /** 设置审批人 */
    setApprover() {
      this.$refs.workFlowDialogRef.openWorkflow(2);
    },
    // 打开导入仓库
    imporStorehouse() {
      this.$refs.imporStorehouse.open();
    },
    //获取设置信息
    getConfigData(data){
      if(data){
        this.configDataHandle(data);
      }else{
        SettingApi.getTenantConfigData().then((res) =>{
          if(res&&res.data){
            this.configDataHandle(res.data);
          }
        }).catch((err)=>{
          console.log(err)
        });
      }
    },
    configDataHandle(data={}){
      this.configData=data;
      let {sparePartConfig={}}=data;
      //备件库模式 true多备件库 false单备件库
      this.sparepart2=sparePartConfig.sparepart2?1:0;
      //出库类型
      this.personalRepertory=sparePartConfig.personalRepertory;
    },
    /*--------------------- 备件库模式 ---------------------*/
    /* 设置备件库模式 */
    sparepart2Change(value){
      if(value==1){
        this.$confirm(this.$t('sparepart.setting.repertory.tips4'), this.$t('common.base.toast'), {
          confirmButtonText: this.$t('common.base.confirm'),
          cancelButtonText: this.$t('common.base.cancel'),
          type: 'warning'
        }).then(() => {
          this.saveSparepart2('sparepart2',true,()=>{

            this.saveSparepart2('personalRepertory',true,()=>{
              Platform.alert(this.$t('sparepart.setting.repertory.tips5'));
              window.location.reload();
            })

          })
        }).catch(() => {
          this.sparepart2=0;
        });
      }
    },
    /* 是否开启个人备件库 */
    personalRepertoryChange(value){
      if(value&&this.sparepart2!==1){
        this.personalRepertory=!value;
        Platform.alert(this.$t('sparepart.setting.repertory.tips6'));
        return;
      }
      this.$confirm(this.$t('sparepart.setting.repertory.tips7'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(() => {
        this.saveSparepart2('personalRepertory',value)
      }).catch(() => {
        this.personalRepertory=!value;
      });
    },
    saveSparepart2(name,value,callback){
      this.pageLoading();
      let params={
        flow: name,
        state: value
      }
      SettingApi.saveSettingSparepart2(params).then((res) =>{
        if(res&&res.status===1){
          Platform.alert(res?.message|| this.$t('sparepart.setting.repertory.tips8'));
        }else{
          callback && callback();
          //this.$notify({ title: '成功', message: res.message, type: 'success' });
        }
        this.pageLoadingClose();
        this.getConfigData(res.data);
      }).catch((err)=>{
        console.log(err)
        Platform.alert(this.$t('sparepart.setting.repertory.tips8'));
        this.pageLoadingClose();
        this.getConfigData();
      })
    },
    /*--------------------- 仓库设置 ---------------------*/
    /* 获取仓库设置列表 */
    resetSearch(){
      this.keyword='';
      this.getTableData();
    },
    getTableData(){
      this.loading.tableData=true;
      SettingApi.getRepertoryAllRepertory({keyword:this.keyword}).then((res) =>{
        if(res&&res.result){
          this.tableData=res.result.map(item=>{
            item.addressDes= formatAddress(item);
            item.teamDes='';
            if(item.teamIds && item.teamIds.length>0){
                item.teamDes=item.teamIds.map(t=>t.name).join('  ');
            }
            item.managerDes='';
            if(item.manager && item.manager.length>0){
                item.managerDes=item.manager.map(m=>m.displayName).join('  ');
            }
            return item;
          });
        }else{
          this.tableData=[];
        }
        this.loading.tableData=false;
      }).catch((err)=>{
        console.log(err)
        this.tableData=[];
        this.loading.tableData=false;
      });
    },
    delHandle(item){
      this.$confirm(this.$t('sparepart.setting.repertory.tips9'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(() => {
        this.pageLoading();
        SettingApi.delRepertoryRepertory(item.id).then((res) =>{
          if(res&&res.status===0){
            this.getTableData()
          }else{
            Platform.alert(res?.message|| this.$t('sparepart.setting.repertory.tips10'));
          }
          this.pageLoadingClose();
        }).catch((err)=>{
          console.log(err)
          Platform.alert(this.$t('sparepart.setting.repertory.tips10'));
          this.pageLoadingClose();
        })
      }).catch(() => {});
    },
    addHandle(){
    //  this.getManagerList();
      //this.getTeamTree();
      this.currentId = ''
      this.isRepertoryModal=true;
    },
    editHandle(item){
    //  this.getManagerList();
      this.currentId=item.id;
      SettingApi.getRepertoryData(item.id).then((res) =>{
        if(res&&res.status===0&&res.data){
          let {data}=res;
          //this.repertoryForm
          let manager=data.manager||[];
          let teamIds=data.teamIds||[];
          //data.teamIds=[];
          data.manager=manager.map(item=>{
            item.label = item.displayName
            return item;
          });
          for(let n in this.repertoryForm){
            this.repertoryForm[n]=data[n];
          }
          //this.getTeamTree(teamIds.map(item=>item.id));
          this.isRepertoryModal=true;
        }else{
          Platform.alert(res?.message||this.$t('sparepart.setting.repertory.tips10'));
        }
      }).catch((err)=>{
        console.log(err)
        Platform.alert(this.$t('sparepart.setting.repertory.tips10'));
      });
    },
    submitRepertory(formName){
      this.$refs[formName].validate((valid) => {
        if (!valid) return false;
        let form=this.repertoryForm;
        let params={...form};
        if(params.teamIds){
          params.teamIds=params.teamIds.map(item=>{
            return {id:item.id,name:item.name||item.tagName};
          });
        }
        if(params.manager){
          params.manager = params.manager.map(item=>{
            let { displayName, head, staffId, userId } = item;
            return { displayName, head, staffId, userId };
          });
        }
        let saveApi="saveSparepartRepertory"
        if(this.currentId){
          params.id=this.currentId;
          saveApi="updateSparepartRepertory"
        }
        this.pageLoading();
        SettingApi[saveApi](params).then((res) =>{
          if(res&&res.status===0){
            this.getTableData();
            this.isRepertoryModal=false;
          }else{
            Platform.alert(res?.message||this.$t('sparepart.setting.repertory.tips10'));
          }
          this.pageLoadingClose();
        }).catch((err)=>{
          console.log(err)
          Platform.alert(this.$t('sparepart.setting.repertory.tips10'));
          this.pageLoadingClose();
        })
      });
    },
    searchTemplate(params) {
      const pms = params || {};
      return SettingApi.getCandidateManagers(pms)
        .then((res) => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map((template) =>
              Object.freeze({
                label: template.displayName,
                value: template.userId,
                ...template,
              })
            );
          }
          return res;
        })
        .catch((e) => console.error(e));
    },
    getManagerList(){
      this.managerList=[];
      this.managerObj={};
      SettingApi.getCandidateManagers({pageNum:1, pageSize:5000}).then((res) =>{
        if(res&&res.list){
          console.log(res.list)
          this.managerList=res.list.map(item=>{
            this.managerObj[item.userId]=item;
            return item;
          });
        }
      })
    },
    getTeamTree(teamIds=[]){
      this.securityTagTree=[];
      SettingApi.getSettingUserSeeAllOrg().then((res1) =>{
        SettingApi.getSecurityTagTree({seeAllOrg:res1.data,pageNum:1}).then((res2) =>{
          console.log('获取role',res2)
          this.securityTagObj={};
          this.repertoryForm.teamIds=[];
          this.securityTagTree=this.treeSecondaryTreatment(res2.list,teamIds);
          console.log(this.securityTagTree)
          // let treeText=JSON.stringify(res2.list).replace(/\[\]/g,"null");
          // console.log('获取role2',JSON.parse(treeText))
        })
      })
    },
    treeSecondaryTreatment(list=[],ids=[],levelID=[]){
      let arr=[];
      list.forEach(item=>{
        if(ids.includes(item.id)){
          this.repertoryForm.teamIds.push([...levelID,item.id]);
        }
        this.securityTagObj[item.id]=item;
        let children=null;
        if(item.children&&item.children.length>0){
          children=this.treeSecondaryTreatment(item.children,ids,[...levelID,item.id]);
        }
        item.children=children;
        arr.push(item)
      });
      return arr;
    },
    teamIdsChange(value){
      console.log(value)
    },
    update(data){
      console.log(data);
      let {newValue}=data||{};
      if(newValue){
        let arr=['country','province','city','dist','address','latitude','longitude'];
        arr.forEach(item=>{
          this.repertoryForm[item]=newValue[item];
        });
      }
    },
    /* 团队选者 */
    teamUpdate(event) {
      console.log(event);
      this.repertoryForm.teamIds = event.map(item => {return item});
      console.log(this.repertoryForm)
      // let ids = event.map(item => {
      //   return item.id
      // }).join(',')
    },
    /*--------------------- 其他 ---------------------*/
    /* 全页loading */
    pageLoading(text="loading",spinner="el-icon-loading",background="rgba(255, 255, 255, 0.7)"){
      this.loading.page = this.$loading({
        lock: true,
        text: text,
        spinner: spinner,
        background: background
      });
    },
    pageLoadingClose(){
      this.loading.page.close();
    },
  }
}
</script>

<style lang="scss">

.repertory_radio_box{
  margin-top: 15px;
  .radio_text{
    padding-left:24px;
    font-size: 12px;
    line-height: 18px;
    margin-top: 8px
  }
}
.setting_search_box{
  overflow: hidden;
  margin-bottom:10px;
  .search_input{
    width: 200px;
    float: left;
    margin-right: 10px;
  }
  .el-button{
    float: left;
  }
  .search-add{
    float: right;
  }
}
.bm-picker-map{
  height: 100vh;
}
.modal_box .biz-team-select-block .biz-team-select{
  height: auto;
  min-height: 32px;
}

.setting-box-warp-part {
  .el-table {
    .open-data {
      margin-right: 0;
    }
  }
}
.setting-box {
  .box-item-wrap {
    .box-item {
      float: left;
      .item-title {
        font-size: 14px;
        font-weight: 700;
        line-height: 18px;
      }
      .item-text {
        font-size: 12px;
        line-height: 28px;
        margin-top: 5px;
      }
    }
    .el-button {
      float: right;
      margin-top:20px
    }
  }
}
</style>
